package com.example.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.bean.User;
import com.example.config.AuthAccess;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @title: JwtInterceptor
 * @Author wjf
 * @Date: 2022/9/23 13:33
 * @Version 1.0
 */
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("token");
        //如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }else {
           HandlerMethod h = (HandlerMethod) handler;
            AuthAccess authAccess = h.getMethodAnnotation(AuthAccess.class);
            if (authAccess!=null){
                return true;
            }
        }
        //执行认证
        if (StringUtils.isBlank(token)) {
            throw new RuntimeException("无token,请重新登录"); // 抛出异常，"无token,请重新登录"
        }
        //获取 token 中的 user id
        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException e) {
            throw new RuntimeException("token验证失败，请重新登录");
        }
        //根据token中的userId查询数据库
        User user = userService.getById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在,请重新登录");
        }
        //用户密码加签证 token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            jwtVerifier.verify(token);  //验证token
        } catch (JWTVerificationException e) {
            throw new RuntimeException("token验证失败,请重新登录");
        }
        return true;
    }
}
